package org.example;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.zone.ZoneRules;

public class CalculateTimeSpan {

    private final static ZoneId zoneId = ZoneId.of("America/New_York");

    public static long calculateTimeSpan(ZonedDateTime startTime, ZonedDateTime endTime){
        // 先计算两个时间之间的差
        Duration between = Duration.between(startTime, endTime);
        long seconds = between.getSeconds();
        if (!isDaylightTime(startTime.toLocalDateTime(), zoneId)
                && isDaylightTime(endTime.toLocalDateTime(),zoneId)){
            seconds -= 3600; // 夏令时减去一小时
        }
        // 时长以分钟为单位，不足一分钟的按一分钟计算
        return (long) Math.ceil(seconds);
    }



    /**
     * 传入指定时间和时区,判断是否处于夏令时之中
     * @param localDateTime 本地时间
     * @param zoneId 时区Id
     * @return
     */
    public static boolean isDaylightTime(LocalDateTime localDateTime, ZoneId zoneId) {
        ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
        ZoneRules rules = zoneId.getRules();
        return rules.isDaylightSavings(zonedDateTime.toInstant());
    }
}
